<template>
    <el-card style="width: 90%;margin-bottom: 20px" shadow="always">
        <h2>个人信息</h2>
        <el-form :model="form" label-width="auto" style="max-width: 100%">
            <el-form-item label="头像">
                <img :src="form.image" style="width: 75px;height: 75px;" />
                <el-link style="margin-left: 10px;" :underline="false" type="primary"
                    @click="profilePictureDialogVisible = true">
                    <el-icon style="margin-left: 10px;">
                        <ArrowRight />
                    </el-icon>
                </el-link>
            </el-form-item>
            <el-form-item label="姓名">
                {{ form.name }}
                <el-link style="margin-left: 10px;" type="primary" :underline="false"
                    @click="nameModifyDialogVisible = true"><el-icon style="margin-left: 10px;">
                        <ArrowRight />
                    </el-icon></el-link>
            </el-form-item>
            <el-form-item label="性别">
                {{ form.gender == '1'? '男' : '女' }}
            </el-form-item>
            <el-form-item label="账号">
                {{ form.account }}
                <el-link style="margin-left: 10px;" type="primary" :underline="false"
                    @click="accountModifyDialogVisible = true"><el-icon style="margin-left: 10px;">
                        <ArrowRight />
                    </el-icon></el-link>
            </el-form-item>
            <el-form-item label="工资">
                <div>
                    当月工资:{{ form.salary }}元
                </div>
                <el-link style="margin-left: 10px;" type="primary" @click="salaryChangeDialogVisible = true"
                    :underline="false"><el-icon style="margin-left: 10px;">
                        <ArrowRight />
                    </el-icon></el-link>
            </el-form-item>
            <el-form-item label="已扣工资">当月已扣:{{ form.deductSalary }}元</el-form-item>
            <el-form-item label="培训得分">{{ form.trainingScore }}</el-form-item>
            <el-form-item label="创建时间">{{ form.createTime }}</el-form-item>
        </el-form>
    </el-card>
    <!-- 头像更改对话框 -->
    <el-dialog v-model="profilePictureDialogVisible" title="头像修改"  draggable>
        <el-upload :action="getEmpImageUrl" :show-file-list="false" :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload" class="avatar-uploader">
            <img v-if="form.image" :src="form.image" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon">
                <Plus />
            </el-icon>
        </el-upload>
        <el-button style="margin-top: 10px;margin-left: 50px;" type="primary"
            @click="profilePictureDialogVisible = false">确定</el-button>
    </el-dialog>
    <!-- 姓名修改对话框 -->
    <el-dialog v-model="nameModifyDialogVisible" title="姓名修改" style="width: 20%;" draggable>
        <el-form :rules="nameModifyRule" :model="nameModifyForm">
            <el-form-item label="姓名修改" prop="nameModify">
                <el-input v-model="nameModifyForm.nameModify" style="width: 170px;" placeholder="请输入你要修改的名字" />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" style="margin-top: 10px;margin-left: 100px;"
                    @click="modifyEmpNameAccountMessage">
                    确定
                </el-button>
            </el-form-item>
        </el-form>
    </el-dialog>
    <!-- 修改账号对话框 -->
    <el-dialog v-model="accountModifyDialogVisible" title="账号修改" style="width: 20%;" draggable>
        <el-form :rules="nameModifyRule" :model="nameModifyForm">
            <el-form-item label="账号修改" prop="accountModify">
                <el-input v-model="nameModifyForm.accountModify" style="width: 170px;" placeholder="请输入你要修改的账号"/>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" style="margin-top: 10px;margin-left: 100px;"
                    @click="modifyEmpNameAccountMessage">
                    确定
                </el-button>
            </el-form-item>
        </el-form>
    </el-dialog>
    <!-- 查看工资对话框 -->
    <el-dialog v-model="salaryChangeDialogVisible" title="工资详情" style="width: 60%;" draggable>
        <el-form :model="salaryChangeForm" :inline="true" style="margin-bottom: 10px;">
            <el-form-item label="结算日期">
                <el-date-picker v-model="salaryChangeForm.date" clearable value-format="YYYY-MM-DD" type="daterange"
                    placeholder="选择日期" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"
                    style="width: 350px; margin-left: 10px"></el-date-picker>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="getEmpSalaryMessage">查询</el-button>
                <el-button type="info" @click="clearSalaryChangeForm">清空</el-button>
            </el-form-item>
        </el-form>
        <div style="margin-bottom: 10px;">
            你当前的工资是:{{ form.salary }}元 当前累积扣除的工资是:{{ form.deductSalary }}元
        </div>
        <el-table :data="tableData" border style="width: 100%;margin-bottom: 10px;">
            <el-table-column type="index" label="id" width="100" />
            <el-table-column prop="salaryDate" label="结算日期" width="250" />
            <el-table-column prop="deductSalary" label="扣除工资" width="250" />
            <el-table-column prop="salary" label="结算工资" width="250" />
        </el-table>
        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
            :page-sizes="[5, 10, 15, 20]" :size="size" :disabled="disabled" :background="background"
            layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
            @current-change="handleCurrentChange" />
    </el-dialog>
</template>

<script setup lang="ts">
import { onMounted, ref } from 'vue';
import { ElMessage } from 'element-plus';
import type { FormRules, ComponentSize } from 'element-plus';
import { empAccount } from '@/store';
import axios from '@/utils/request';
import { ArrowRight, Plus } from '@element-plus/icons-vue';
import type { UploadProps } from 'element-plus';

// 响应式变量定义
const profilePictureDialogVisible = ref(false);
const nameModifyDialogVisible = ref(false);
const accountModifyDialogVisible = ref(false);
const salaryChangeDialogVisible = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const size = ref<ComponentSize>('default');
const background = ref(true);
const disabled = ref(false);
const empAccountStore = empAccount();
const getEmpImageUrl = `/api/emp/upload/${empAccountStore.$state.account}`;
const tableData = ref([]);
const salaryChangeForm = ref({
    date: ['','']
});
const clearSalaryChangeForm = () => {
    salaryChangeForm.value.date = ['',''];
    //重新获取数据
    getEmpSalaryMessage();
};
const form = ref({
    id: '',
    image: '',
    name: '',
    gender: '',
    account: '',
    salary: '',
    createTime: '',
    deductSalary: '',
    trainingScore: '',
});
const nameModifyRule = ref<FormRules>({
    nameModify: [
        { required: true, message: '姓名不能为空', trigger: 'blur' }
    ],
    accountModify: [
        { required: true, message: '账号不能为空', trigger: 'blur' }
    ],
});
const nameModifyForm = ref({
    nameModify: '',
    accountModify: ''
});
nameModifyForm.value.accountModify=empAccountStore.$state.account;
nameModifyForm.value.nameModify=empAccountStore.$state.name;
// 方法定义
//当前页数发生改变
const handleSizeChange = (val: number) => {
    pageSize.value = val;
    //重新获取数据
    getEmpSalaryMessage();
};
//当前页发生改变
const handleCurrentChange = (val: number) => {
   currentPage.value = val;
   //重新获取数据
   getEmpSalaryMessage();
};
// 获取员工信息
const getEmpMessage = async () => {
    try {
        const result = await axios.get(`/emp/${empAccountStore.$state.account}`);
        if (result.data.code === 1) {
            form.value = result.data.data;
        } else {
            ElMessage.error('员工信息获取失败')
        }
    } catch (error) {
        console.error('获取员工信息时发生错误:', error);
        ElMessage.error('获取信息失败，请稍后再试');
    }
};
//员工修改部分信息
const modifyEmpNameAccountMessage = async () => {
    try {
        const result = await axios.put(`/emp/${form.value.id}`, {
            id : form.value.id,
            name: nameModifyForm.value.nameModify,
            account: nameModifyForm.value.accountModify,
        });
        if (result.data.code === 1) {
            ElMessage.success('修改成功');
            //关闭对话框
            nameModifyDialogVisible.value = false;
            accountModifyDialogVisible.value = false;
            //刷新界面
            getEmpMessage();
            //储存账号信息
            empAccountStore.$state.account = nameModifyForm.value.accountModify;
        } else {
            ElMessage.error('修改失败');
        }
    } catch (error) {
        console.error('修改员工信息时发生错误:', error);
        ElMessage.error('修改失败，请稍后再试');
    }
};
const handleAvatarSuccess: UploadProps['onSuccess'] = (response) => {
    form.value.image=response.data;
     //修改成功
     ElMessage.success('修改成功');
     //获得信息
     getEmpMessage();
};

const beforeAvatarUpload: UploadProps['beforeUpload'] = (file) => {
    const allowedImageTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/svg+xml'];
    const isImage = allowedImageTypes.includes(file.type);
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isImage) {
        ElMessage.error("上传的文件必须是图片格式!");
    }
    if (!isLt2M) {
        ElMessage.error("上传的图片大小不能超过 2MB!");
    }
    return isImage && isLt2M;
};
//获取员工工资信息
const getEmpSalaryMessage = async () => {
    try {
        const result = await axios.get(`/emp/salary/${empAccountStore.$state.account}`, {
            params: {
                page: currentPage.value,
                pageSize: pageSize.value,
                startDate: salaryChangeForm.value.date[0],
                endDate: salaryChangeForm.value.date[1]
            }
        });
        if (result.data.code === 1) {
            if(salaryChangeForm.value.date[0]!==''&&salaryChangeForm.value.date[1]!==''){
                ElMessage.success('查询成功');
            }
            tableData.value = result.data.data.rows;
            total.value = result.data.data.total;
        } else {
            ElMessage.error('查询失败')
        }
    } catch (error) {
        console.error('获取员工信息时发生错误:', error);
        ElMessage.error('获取信息失败，请稍后再试');
    }
};
</script>
<style scoped>
body {
    font-family: Arial, sans-serif;
    background-color: #f4f4f4;
    padding: 20px;
    line-height: 1.6;
}

.el-tabs {
    border-radius: 8px;
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
    background-color: white;
    padding: 15px;
    overflow: hidden;
}

.el-tabs__header {
    border-bottom: 1px solid #ebeef5;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 15px;
}

.el-tabs__item {
    padding: 8px 15px;
    font-size: 15px;
    color: #333;
    transition: all 0.3s ease;
}

.el-tabs__item:hover {
    color: #409EFF;
    cursor: pointer;
}

.el-tabs__item::after {
    content: "";
    position: absolute;
    bottom: -1px;
    left: 0;
    width: 0;
    height: 2px;
    background-color: #409EFF;
    transition: width 0.3s ease;
}

.el-tabs__item:hover::after {
    width: 100%;
}

.el-tabs__item.is-active {
    color: #409EFF;
    font-weight: bold;
}

.el-tabs__item.is-active::after {
    width: 100%;
}

.el-tabs__content {
    padding: 15px;
}

.el-tabs__item {
    margin-right: 15px;
}
</style>